<?php
/**
 * Here is your custom functions.
 */
if (!function_exists('ok_rsp')) {
    function ok_rsp($msg = '', $data = [], $code = 0) {
        return json_encode([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
}

if (!function_exists('err_rsp')) {
    function err_rsp ($msg, $code = 400, $data = []) {
        return json_encode([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
}

if (!function_exists('e_rsp')) {
    function e_rsp(Exception $e, $data = []) {
        if (getenv('APP_DEBUG')) {
            echo $e->getMessage() . $e->getTraceAsString();
        }

        return json_encode([
            'code' => $e->getCode() ?? 400,
            'msg' => $e->getMessage(),
            'data' => $data
        ]);
    }
}

if (!function_exists('get_user_id')) {
    function get_user_id() {
        $request = request();
        $token = $request->header('token');

        if (empty($token)) {
            $token = $request->input('token');
        }
        return \app\services\TokenService::getUserId($token);
    }
}

if (!function_exists('build_oss_url')) {
    function build_oss_url($url) {
        if (empty($url)) {
            return $url;
        }

        if (strpos($url, 'http') === 0 || strpos($url, 'https') === 0) {
            return $url;
        }

        $ossUrl = getenv('OSS_URL');

        if (strpos($url, '/') === 0) {
            return $ossUrl . $url;
        }

        return $ossUrl . '/' . $url;
    }
}

if (!function_exists('get_current_language')) {
    function get_current_language() {
        $request = request();
        return $request->header('Accept-Language');
    }
}

if (!function_exists('build_edit_tools_url')) {
    function build_edit_tools_url($cmd, $id = 0) {
        $request = request();
        $token = $request->header('token');
        return getenv('TOOLS_URL') . "?token={$token}&command={$cmd}" . ($id > 0 ? '&work_id=' . $id : '');
    }
}

if (!function_exists('get_request_type')) {
    function get_request_type() {
        $request = request();
        return $request->header('Request-Type');
    }
}

if (!function_exists('format_mobile')) {
    function format_mobile($mobile) {
        if ($mobile) {
            return substr($mobile, 0, 3) . '****' . substr($mobile, 7);
        }

        return $mobile;
    }
}

if (!function_exists('format_email')) {
    function format_email($email) {
        if ($email) {
            // 分离邮箱的用户名和域名部分
            list($username, $domain) = explode('@', $email);

            // 确定需要隐藏的用户名部分
            $length = strlen($username);
            if ($length <= 2) {
                // 如果用户名长度小于等于 2，保留第一个字符，其余用星号替换
                $hidden_username = $username[0] . str_repeat('*', $length - 1);
            } else {
                // 保留前两个和后一个字符，中间用星号替换
                $hidden_username = substr($username, 0, 2) . str_repeat('*', $length - 3) . substr($username, -1);
            }

            // 重新组合隐藏后的用户名和域名
            $email = $hidden_username . '@' . $domain;
        }

        return $email;
    }
}

if (!function_exists('replace_content')) {
    function replace_content($content) {
        return preg_replace_callback('/src="([^"]+)"/', function ($matches) {
            $url = $matches[1];
            if (strpos($url, 'http') === 0 || strpos($url, 'https') === 0) {
                return $matches[0]; // 不替换
            }
            return 'src="' . getenv('APP_URL') . $url . '"'; // 替换
        }, $content);
    }
}

if (!function_exists('format_bank_card')) {
    function format_bank_card($mobile) {
        if ($mobile) {
            return substr($mobile, 0, 4) . '********' . substr($mobile, 12);
        }

        return $mobile;
    }
}

function admin_public_path(string $path = ''): string
{
    static $publicPath = '';
    if (!$publicPath) {
        $publicPath = \config('app.admin_public_path');
    }

    $path = str_replace('/app/admin', '', $path);

    return path_combine($publicPath, $path);
}

/**
 * 从 URL 中提取文件名
 *
 * @param string $url 要解析的完整 URL
 * @param bool $stripQuery 是否移除查询参数 (默认: true)
 * @param bool $sanitize 是否清理文件名 (默认: true)
 * @return string|false 提取到的文件名，失败时返回 false
 */
function getFilenameFromUrl(string $url, bool $stripQuery = true, bool $sanitize = true) {
    // 解析URL获取路径部分
    $path = parse_url($url, PHP_URL_PATH);

    if ($path === null) {
        return false;
    }

    // 提取文件名
    $filename = basename($path);

    // 可选：移除查询参数（如果存在于文件名中）
    if ($stripQuery && str_contains($filename, '?')) {
        $filename = explode('?', $filename, 2)[0];
    }

    // 可选：清理文件名（移除非法字符）
    if ($sanitize) {
        $filename = preg_replace('/[\\\\\/:\*\?"<>\|]/', '', $filename);
    }

    return empty($filename) ? false : $filename;
}

function formatFileSize($filePath) {
    // 检查文件是否存在
    if (!file_exists($filePath)) {
        return "文件不存在";
    }

    // 获取文件大小（字节）
    $bytes = filesize($filePath);

    // 定义单位和对应的字节数
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $unitIndex = 0;

    // 循环转换单位直到合适的大小
    while ($bytes >= 1024 && $unitIndex < count($units) - 1) {
        $bytes /= 1024;
        $unitIndex++;
    }

    // 格式化结果（保留两位小数）
    return round($bytes, 2) . ' ' . $units[$unitIndex];
}

if (!function_exists('raw_json_rsp')) {
    function raw_json_rsp($data) {
        return json_encode($data);
    }
}

if (!function_exists('full_url')) {
    function full_url($url) {
        if (empty($url)) {
            return $url;
        }
        if (strpos($url, 'http') !== false) {
            return $url;
        }
        return getenv('APP_URL') . $url;
    }
}

if (!function_exists('cartesian_product')) {
    function cartesian_product($arrays) {
        $result = [[]];

        foreach ($arrays as $array) {
            $tmp = [];

            foreach ($result as $resultItem) {
                foreach ($array as $item) {
                    $tmp[] = array_merge($resultItem, [$item]);
                }
            }

            $result = $tmp;
        }

        return $result;
    }
}

if (!function_exists('diff_time')) {
    function diff_time($datetime) {
        $diff = (new DateTime())->diff(new DateTime($datetime));
        $year = $diff->y;
        if ($year > 0) {
            return $year . '年前';
        }
        $month = $diff->m;

        if ($month > 0) {
            return $month . '月前';
        }

        $day = $diff->days;

        if ($day > 0) {
            return $day . '天前';
        }
        $hour = $diff->h;

        if ($hour > 0) {
            return $hour . '小时前';
        }

        $minute = $diff->i;

        if ($minute > 0) {
            return $minute . '分钟前';
        }

        $seconds = $diff->s;

        if ($seconds > 0) {
            return $seconds . '秒前';
        }

        return '刚刚';
    }
}

function myUrlEncode($string) {
    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
    return str_replace($entities, $replacements, urlencode($string));
}

function getWeek($timestamp = null, $prefix = '周')
{
    if (is_null($timestamp)) {
        $timestamp = time();
    }
    $weekArray=array("日","一","二","三","四","五","六"); //先定义一个数组
    return $prefix . $weekArray[date("w", $timestamp)]; //w为星期几的数字形式,这里0为周日
}

function hideTrueName($name)
{
    $hiddenName = str_replace($name[1], "*", $name); // 将第一个字母替换成*号
    return $hiddenName;
}

function hideIdCardNo($no)
{
    return substr($no, 0, 6) . '********' . substr($no, 14);
}


/**
 * 图片拼接函数
 * @param array $images 图片路径数组
 * @param string $direction 拼接方向：'horizontal'(水平) 或 'vertical'(垂直)
 * @param string $outputPath 输出文件路径
 * @param int $spacing 图片间距，默认为0
 * @return bool 是否成功
 */
function mergeImages($images, $direction = 'horizontal', $outputPath = null, $spacing = 0) {
    if (empty($images)) {
        return false;
    }
    
    $imageResources = [];
    $totalWidth = 0;
    $totalHeight = 0;
    $maxWidth = 0;
    $maxHeight = 0;
    
    // 加载所有图片并计算尺寸
    foreach ($images as $imagePath) {
        if (!file_exists($imagePath)) {
            continue;
        }
        
        $imageInfo = getimagesize($imagePath);
        if (!$imageInfo) {
            continue;
        }
        
        $width = $imageInfo[0];
        $height = $imageInfo[1];
        $type = $imageInfo[2];
        
        // 根据图片类型创建资源
        switch ($type) {
            case IMAGETYPE_JPEG:
                $resource = imagecreatefromjpeg($imagePath);
                break;
            case IMAGETYPE_PNG:
                $resource = imagecreatefrompng($imagePath);
                break;
            case IMAGETYPE_GIF:
                $resource = imagecreatefromgif($imagePath);
                break;
            default:
                continue 2;
        }
        
        if (!$resource) {
            continue;
        }
        
        $imageResources[] = [
            'resource' => $resource,
            'width' => $width,
            'height' => $height
        ];
        
        if ($direction === 'horizontal') {
            $totalWidth += $width;
            $maxHeight = max($maxHeight, $height);
        } else {
            $totalHeight += $height;
            $maxWidth = max($maxWidth, $width);
        }
    }
    
    if (empty($imageResources)) {
        return false;
    }
    
    // 添加间距
    $spacingTotal = $spacing * (count($imageResources) - 1);
    if ($direction === 'horizontal') {
        $totalWidth += $spacingTotal;
        $canvasWidth = $totalWidth;
        $canvasHeight = $maxHeight;
    } else {
        $totalHeight += $spacingTotal;
        $canvasWidth = $maxWidth;
        $canvasHeight = $totalHeight;
    }
    
    // 创建画布
    $canvas = imagecreatetruecolor($canvasWidth, $canvasHeight);
    
    // 设置背景为白色
    $white = imagecolorallocate($canvas, 255, 255, 255);
    imagefill($canvas, 0, 0, $white);
    
    // 拼接图片
    $currentX = 0;
    $currentY = 0;
    
    foreach ($imageResources as $imageData) {
        $resource = $imageData['resource'];
        $width = $imageData['width'];
        $height = $imageData['height'];
        
        // 复制图片到画布
        imagecopy($canvas, $resource, $currentX, $currentY, 0, 0, $width, $height);
        
        // 更新位置
        if ($direction === 'horizontal') {
            $currentX += $width + $spacing;
        } else {
            $currentY += $height + $spacing;
        }
        
        // 释放原图片资源
        imagedestroy($resource);
    }
    
    // 输出图片
    if ($outputPath) {
        $ext = strtolower(pathinfo($outputPath, PATHINFO_EXTENSION));
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                $result = imagejpeg($canvas, $outputPath, 90);
                break;
            case 'png':
                $result = imagepng($canvas, $outputPath);
                break;
            case 'gif':
                $result = imagegif($canvas, $outputPath);
                break;
            default:
                $result = imagejpeg($canvas, $outputPath, 90);
        }
    } else {
        // 直接输出到浏览器
        header('Content-Type: image/jpeg');
        $result = imagejpeg($canvas);
    }
    
    // 释放画布资源
    imagedestroy($canvas);
    
    return $result;
}